package com.example.ytc.tools;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.json.JSONException;

import android.content.Context;
import android.content.SharedPreferences;

import com.itconnect.inc.entertainment.R;
import com.example.ytc.clazz.Ivideo;
import com.example.ytc.clazz.Video;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class FavoritDAO {
	private static final String PREFIX = "json";

	public static void save(Context c, Video v) throws Exception {
		SharedPreferences settings = c.getSharedPreferences(c.getResources()
				.getString(R.string.yt_use_id), 0);
		SharedPreferences.Editor editor = settings.edit();
		Gson gson = new Gson();
		int i = 0;
		List<Ivideo> lst = null;
		try {
			lst = get(c);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
		}

		if (lst == null) {
			lst = new ArrayList<Ivideo>();
		} 
		// if video allready exist
		if (!Utils.contains(lst,v.getIvide())) {
			lst.add(v.getIvide());
		} else {
			throw new Exception();
		}
			String json = gson.toJson(lst);
			editor.putString(FavoritDAO.PREFIX, json);
			editor.commit();
		
	}
	public static void remove(Context c, Video v) throws Exception {
		SharedPreferences settings = c.getSharedPreferences(c.getResources()
				.getString(R.string.yt_use_id), 0);
		SharedPreferences.Editor editor = settings.edit();
		Gson gson = new Gson();
		int i = 0;
		List<Ivideo> lst = null;
		try {
			lst = get(c);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
		}

		if (lst == null) {
			lst = new ArrayList<Ivideo>();
		} 
		// if video allready exist
			lst.remove(Utils.getposition(lst,v.getIvide()));
			String json = gson.toJson(lst);
			editor.putString(FavoritDAO.PREFIX, json);
			editor.commit();
		
	}
	public static void clear(Context c) {
		SharedPreferences settings = c.getSharedPreferences(c.getResources()
				.getString(R.string.yt_use_id), 0);
		SharedPreferences.Editor editor = settings.edit();
		editor.clear();
		editor.commit();
	}

	public static List<Ivideo> get(Context c) throws JSONException {
		SharedPreferences settings = c.getSharedPreferences(c.getResources()
				.getString(R.string.yt_use_id), 0);
		Gson gson = new Gson();
		Type listType = new TypeToken<List<Ivideo>>() {
		}.getType();
		String json = settings.getString(FavoritDAO.PREFIX, "");
		List<Ivideo> obj = gson.fromJson(json, listType);
		return obj;
	}

	public static String loadJSONArray(Context c) throws JSONException {
		SharedPreferences settings = c.getSharedPreferences(c.getResources()
				.getString(R.string.yt_use_id), 0);
		return settings.getString(FavoritDAO.PREFIX, null);
	}

}